import 'dart:async';
import 'dart:io';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_application_testview/app_theme.dart';
import 'package:flutter_application_testview/model/heartRate_data.dart';
import 'package:flutter_application_testview/services/background_service.dart';
import 'package:flutter_application_testview/services/logger.dart';
import 'package:provider/provider.dart';
import 'navigation_home_screen.dart';
import 'package:flutter/foundation.dart' show kIsWeb;

void main() async {
  final stopwatch = Stopwatch()..start();

  WidgetsFlutterBinding.ensureInitialized();
  // 初始化后台服务和心率数据单例
  // 添加帧回调监控

  // 并行初始化任务
  await Future.wait([
    _initEssentialServices(),
    Future.delayed(Duration.zero, () => SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown
    ])),
  ]);
  // 设置屏幕方向
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown
  ]);
  debugPrint('🕒 原生启动屏显示时间: ${stopwatch.elapsedMilliseconds}ms');
  runApp(
    MultiProvider(
      providers: [
        // 使用.value方式注入已存在的单例实例
        ChangeNotifierProvider<HeartRateData>.value(
          value: HeartRateData.instance,
        ),
      ],
      child: MyApp(),
    ),
  );
  WidgetsBinding.instance.addPostFrameCallback((_) {
    debugPrint('🚀 首帧渲染完成时间: ${stopwatch.elapsedMilliseconds}ms');
  });
}
// 分离关键初始化流程
 Future<void> _initEssentialServices() async {
final heartRateInstance = HeartRateData.instance;

// 异步初始化日志系统
scheduleMicrotask(() async {
debugPrint('开始初始化日志系统...');
try {
await AppLogger.init();
debugPrint('日志系统初始化成功 ✅');
} catch (e, stack) {
debugPrint('日志系统初始化失败 ❌: $e\n$stack');
}
});

// 其他必要同步初始化...
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
  
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.dark,
      statusBarBrightness:
          !kIsWeb && Platform.isAndroid ? Brightness.dark : Brightness.light,
      systemNavigationBarColor: Colors.white,
      systemNavigationBarDividerColor: Colors.transparent,
      systemNavigationBarIconBrightness: Brightness.dark,
    ));
    return MaterialApp(
      title: '健康监测',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        textTheme: AppTheme.textTheme,
        platform: TargetPlatform.iOS,
      ),
      home: NavigationHomeScreen(),
    );
  }
}

class HexColor extends Color {
  HexColor(final String hexColor) : super(_getColorFromHex(hexColor));

  static int _getColorFromHex(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll('#', '');
    if (hexColor.length == 6) {
      hexColor = 'FF' + hexColor;
    }
    return int.parse(hexColor, radix: 16);
  }
}
